/** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
**/

function checkForUpdate(text){
	
	var update = text.split(',');
	text = update[0];
	var forced = (update.length > 1 && update[1] == 'F');
	
	if (text && CompareVersion(VERSION, text)) {
		logDebug("New version found, triggering prompt for update");
		
		if (forced) {
			forceUpdate();
		} else {
			optionalUpdate();
		}
	}
}

function forceUpdate() {
	Alert.show(str_newer_version, function(){				
		setTimeout(function(){
			widget.openURL(UPDATE_WIDGET_URL + "?timestamp=" + new Date().getTime());
		}, 0);
		setTimeout(window.close, 0);
	}, exit, null, str_soft_menu_exit);
}

function optionalUpdate() {
	Alert.show(str_newer_version, function(){
		setTimeout(function(){
			widget.openURL(UPDATE_WIDGET_URL + "?timestamp=" + new Date().getTime());
		}, 0);
		setTimeout(window.close, 0);
	}, function(){
	});
}

var versionLastUpdateTime = null;

function downloadUpdateTxt(url){	
	if (!OnlineMonitor.isOnline()) {
		return;
	}
	
	try {
		// Enable Universal Browser Read for running in desktop browser
		if (netscape.security.PrivilegeManager.enablePrivilege) 
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {		
	}
	$.ajax({
		type: "GET",
		url: url,
		cache: false,
		success: function( txt ) {
			checkForUpdate(txt);
		}
	});
}


function CompareVersion(myVersion, newVersion) {
	var mySplited = myVersion.toString().split(".");
	var newSplited = newVersion.toString().split(".");
	
	for(var i=0; i<mySplited.length && i<newSplited.length; i++) {
		var my = parseInt(mySplited[i], 10);
		var ne = parseInt(newSplited[i], 10);
		if(ne>my) 
			return true;
		else if(ne<my)
			return false;
		
	}
	
	return false;
}